package lesson4;

import lombok.SneakyThrows;

import java.util.LinkedList;
import java.util.Queue;

public class MyObject {

    private int max;

    private Queue queue;

    public MyObject(int max){
        this.max = max;
        this.queue = new LinkedList();
    }

    public synchronized void put(Object object) throws InterruptedException {
        while (queue.size() == max){
            System.out.println("queue is full");
            wait();
        }
        System.out.println("queue size " + queue.size());
        queue.add(object);
        notifyAll();
    }

    public synchronized void take() throws InterruptedException {
        while (queue.size() == 0){
            System.out.println("queue is empty");
            wait();
        }
        queue.remove();
        notifyAll();
    }

    public static void main(String[] args) {

        MyObject myObject = new MyObject(5);

        Runnable producer = () -> {
            try {
                while(true){
                    myObject.put(new Object());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        Thread thread1 = new Thread(producer);
        Thread thread2 = new Thread(producer);
        thread1.start();
        thread2.start();

        Runnable consumer = () -> {
            try {
                while (true){
                    myObject.take();
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }

        };

        Thread thread3 = new Thread(consumer);
        Thread thread4 = new Thread(consumer);
        Thread thread5 = new Thread(consumer);
        Thread thread6 = new Thread(consumer);
        thread3.start();
        thread4.start();
        thread5.start();
        thread6.start();
    }
}
